package executor

import (
	"gopkg.in/yaml.v3"
	"log"
	"os"
	"path/filepath"
)

type TaskRecorder struct {
	Path    string
	Records map[string]bool
}

func NewRecorder(path string) (*TaskRecorder, error) {
	records := make(map[string]bool)
	var absPath string
	var err error
	if path == "" {
		absPath, err = filepath.Abs("./temp/records.yaml")
	} else {
		absPath, err = filepath.Abs(path)
	}
	if err != nil {
		return nil, err
	}
	_ = os.MkdirAll(filepath.Dir(absPath), os.ModePerm)

	yamlFile, err := os.ReadFile(absPath)
	if err != nil && !os.IsNotExist(err) {
		return nil, err
	}
	if err == nil {
		err = yaml.Unmarshal(yamlFile, &records)
		if err != nil {
			return nil, err
		}
	}
	return &TaskRecorder{
		Records: records,
		Path:    absPath,
	}, nil
}

func (r *TaskRecorder) ClearAll() {
	records := make(map[string]bool)
	r.Records = records
	r.Write()
}

func (r *TaskRecorder) Record(key string) {
	if key == "" {
		return
	}
	r.Records[key] = true
	r.Write()
}

func (r *TaskRecorder) UnRecord(key string) {
	if key == "" {
		return
	}
	delete(r.Records, key)
	r.Write()
}

func (r *TaskRecorder) IsRecord(key string) bool {
	if key == "" {
		return false
	}
	return r.Records[key]
}

func (r *TaskRecorder) Write() {
	data, err := yaml.Marshal(&r.Records)
	if err != nil {
		log.Printf("yamlFile.Get err   #%v ", err)
		return
	}
	err = os.WriteFile(r.Path, data, os.ModePerm)
	if err != nil {
		log.Printf("yamlFile.WriteFile err   #%v ", err)
	}
}
